source("functions.R")
Biological_process_module_UI<-function(id)
{
  ns<-NS(id)
  tagList(
    bscols(widths = 10,div(style="height: 15px;",width = '200px')),
    a("Click to be directed to Gene Ontology Consortium ", href="http://www.geneontology.org/", target="_blank"),
    bscols(widths = 10,div(style="height: 15px;",width = '200px')),
    fluidRow(column(10,DT::dataTableOutput(ns("Enriched_bp")))),
    br(),
    hr(),
    br(),
    fluidRow(
      column(1,
             selectInput(ns("datachoice10")  ,label = h5("Select Data Type"), 
                         choices = list("Excel" = 1, "CSV" = 2),
                         selected = 1)),
      column(1, 
             br(),
             br(),
             downloadButton(ns('download_Enriched_BP_Table'), 'Download Enriched BP Table'))),
    DT::dataTableOutput(ns("filtered_BP")),
    br(),
    br(),
    hr(),
    br(),
    uiOutput(ns("plot_option_bp")),
    uiOutput(ns("plot_category_bp")),
    uiOutput(ns("plot_category_go")),
    downloadButton(ns('download_bp_plot'), 'Download Plot'),
    plotOutput(ns("bp"))
  )
}

Biological_process_module<-function(input,output,session,DE_genes,
                                    organism,dds.fc,combination,wgcna_output)
{
  #Compute the GO terms based on a list for a list of DE genes(uses function enrichGO from clusterprofiler)
  #Construct  a matrix where row->comparison A vs B, C vs D .etc
  # columns (up regulated GO terms, down regulated GO terms)
  #Loop through a similar matrix generated by reactive DE_genes)
  #Filter GO terms for each element in the matrix generated by reactive DE_genes
  #enrichment analysis
  
  combo<-combination()
  print(combo())
  num<-length(combo())
  
  
Enriched_BP<-reactive({
    print("inside biological process line 39")
    print(organism())
    result<-DE_genes()
   
      if(!is.null(wgcna_output()))
      {
        if((length(wgcna_output()$modules())>0))
        {
          enrichment_main("biological process",result(),organism(),dds.fc(),
                          length(combo()),wgcna_output()$modules(),wgcna_output()$WGCNA_matrix(),NULL)
        }
      }
      else
      {
        print("inside biological process line 53")
        print(combination())
        print(unlist(combination()))
        combo<-combination()
        print(combo())
        num<-length(combo())
        print(combo())
        print(num)
        enrichment_main("biological process",result(),organism(),dds.fc(),
                        num,NULL,NULL,NULL)
      }
      
  })
  
  #Display summary of biological process
output$Enriched_bp <- DT::renderDataTable({
    
      result<-Enriched_BP()[[1]]
      
      print(result)
      rows<-num
      modules<-NULL
      WGCNA_matrix<-NULL
      res<-NULL
      
      if(!is.null(wgcna_output()))
      {
        if((length(wgcna_output()$modules())>0))
        {
          modules<-as.data.frame(table(wgcna_output()$modules()))
          colnames(modules)<-c("Var1","number")
          
          entry<-c(as.vector(combo()), as.vector(modules$Var1))
          print(entry)
          rows<-length(entry)
          
          res<-data.frame(matrix(NA, nrow = rows, ncol = 3))
          colnames(res)<-c('Up regulated','Down regulated','Regulated')
          
          
          print(modules$Var1)
          rownames(res)<-lapply(1:rows, function(i) {
            unlist(entry[i])
            
          })
          
          for(i in 1:length(combo()))
          {
            res[i,1]<-nrow(as.data.frame(result[[i]][[1]]))
            res[i,2]<-nrow(as.data.frame(result[[i]][[2]]))
            res[i,3]<-0
          }
          
          for(i in 1+length(combo()):nrow(modules))
          {
            print('res')
            print(result[[i]][[3]])
            res[i,1:2]<-0
            res[i,3]<-nrow(as.data.frame(result[[i]][3]))
            
          }
        }
      }
      else
      {
        res<-data.frame(matrix(NA, nrow = length(combo()), ncol = 2))
        rownames(res)<-lapply(1:length(combo()), function(i) {
          print(combo())
          combo()[[i]]
          
        })
        colnames(res)<-c('Enriched BP for Up-reg genes','Enriched BP for Down-reg genes')
        print(res)
        print(res[1,1])
        for(i in 1:length(combo()))
        {
          print(nrow(as.data.frame(result[[i]][[1]])))
          res[i,1]<-nrow(as.data.frame(result[[i]][[1]]))
          res[i,2]<-nrow(as.data.frame(result[[i]][[2]]))
        }
        
      }
      
      print(res)
      DT::datatable(res,class = 'cell-border stripe',
                    selection = list(mode='single',target = 'cell'),
                    extensions = list('Scroller'=NULL,'Buttons'=NULL),
                    options = list(deferRender = TRUE,scrollX = TRUE,scrollY = 150,scroller = TRUE,dom = 'Bfrtip',
                                   buttons = list('copy', list(extend = 'collection',buttons = c('csv', 'excel', 'pdf'),
                                                               text = 'Download table'))),
                    
                    escape = FALSE
      )
    
  })
  
  #Display GO terms for the selected comparison
  observeEvent(input$Enriched_bp_cell_clicked,{
    print('hey')
    print(input$Enriched_bp_cells_selected)
    print(input$Enriched_bp_cell_clicked)
    selected <- input$Enriched_bp_cells_selected
    row<-selected[1]
    print('row')
    print(row)
    col<-selected[2]
    print('col')
    print(col)
    if(length(selected)>0){
      
      output$filtered_BP <- DT::renderDataTable({
        print('hey')
        result<-Enriched_BP()[[1]]
        df<-as.data.frame(result[[row]][[col]])
        
        print(head(df))
        DT::datatable(df,class = 'cell-border stripe',
                      selection = list(target = 'column'),
                      extensions = list('Scroller'=NULL,'Buttons'=NULL),
                      options = list(deferRender = TRUE,scrollX = TRUE,scrollY = 150,scroller = TRUE,dom = 'Bfrtip',
                                     buttons = list('copy')))
        
        
        
      })
      #download button
      output$download_Enriched_BP_Table <- downloadHandler(
        
        filename = function() 
        {
          if(as.numeric(input$datachoice10==1)){
          condition <-combo()[[row]]
          if(col==1) paste('Up regulated BP for ',condition,'.xlsx')
          else if(col==2) paste('Down regulated BP for ',condition,'.xlsx') 
          }
          else {
            condition <-combo()[[row]]
            if(col==1) paste('Up regulated BP for ',condition,'.csv')
            else if(col==2) paste('Down regulated BP for ',condition,'.csv') 
          }
          
        },
        content = function(file) {
          #sort by adjusted p value.
          print('heyho')
          result<-Enriched_BP()[[1]]
          
          df<-as.data.frame(result[[row]][[col]])
          nam<-'Sheet1'
          condition <-combo()[[row]]
          condition<-str_replace_all(condition,"[^[:alnum:]]",".")
          if(col==1) nam<-paste('Up regulated BP for ',condition)
          else if(col==2) nam<-paste('Down regulated BP for ',condition)
          if(as.numeric(input$datachoice10==1)){
            M <- as.matrix(df)
            wb <- createWorkbook()
            addWorksheet(wb, sheetName = "Biological Processes")
            writeData(wb = wb, sheet = 1, x = M, colNames = T, rowNames = T)
            saveWorkbook(wb, file)
          }
          else{
            write.csv(df, file)
          }
          
        }
        
      )
      
      output$plot_category_bp<-renderUI({
        textInput(session$ns("category_bp"),label = h6("Enter number of categories to display"), 
                  value = "10") 
      })
      output$plot_category_go<-renderUI({
        textInput(session$ns("category_go"),label = h6("Enter number of GO levels to display"), 
                  value = "") 
      })
      print(as.numeric(input$category_bp))
      
      #Display boxplot of to 10 GO term of selected comparison
      bpplot<-reactive(
      {
        result<-Enriched_BP()[[2]] #obj
        res<-Enriched_BP()[[1]]
        req(input$category_bp)
        
        if(nrow(res[[row]][[col]]) == 0){
          warning("No Data available for plotting")
        }
        else if(nrow(res[[row]][[1]]) == 0 && nrow(res[[row]][[2]] != 0)){
          enrichment_plot("biological process",result,res,row,1,input$category_bp,input$category_go)
        }
        else{
          enrichment_plot("biological process",result,res,row,col,input$category_bp,input$category_go)
        }
      })
        
      output$bp<- renderPlot({
        bpplot()
      })
      output$download_bp_plot <- downloadHandler(
        
        filename =function()
        {
          condition <-combo()[[row]]
          if(col==1) paste('Barplot of Up regulated BP for ',condition,'.pdf')
          else if(col==2) paste(' Barplot of Down regulated BP for ',condition,'.pdf')
        },
        content = function(file) {
          req(input$category_bp)


            ggsave(file,bpplot())#,width=800, height=500)
          
          #dev.off()
          
          
        })
    }
  })
  return(list(
    Enriched_BP_table=reactive({Enriched_BP()[[1]]}),
    Enriched_BP_obj=reactive({Enriched_BP()[[2]]})
  )
    
  )
}